package com.imprenta.bean;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.Serializable;

import javax.faces.application.FacesMessage;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;

import org.primefaces.event.FileUploadEvent;
import org.primefaces.model.UploadedFile;

import com.imprenta.ejb.EjbFileUpload;
import com.imprenta.helpers.MessagesHelper;
import com.imprenta.helpers.SessionHelper;
import com.imprenta.helpers.UtilHelper;
import com.imprenta.model.ResumenPedidoBase;

public class FileUploadBean implements Serializable{

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	/**
	 * @return the file
	 */
	public UploadedFile getFile() {
		return file;
	}

	/**
	 * @param file the file to set
	 */
	public void setFile(UploadedFile file) {
		this.file = file;
	}
	
	/**
	 * @return the disable
	 */
	public boolean isDisable() {
		return disable;
	}

	/**
	 * @param disable the disable to set
	 */
	public void setDisable(boolean disable) {
		this.disable = disable;
	}
	public FileUploadBean() {
		// TODO Auto-generated constructor stub
		//this.disable = true;
	}
	public void upload(){
		
		if (file != null) {
			if (this.file.getFileName().toLowerCase().endsWith(".jpg")) {
				try {
					TransferFile(getFile().getFileName(), getFile().getInputstream());
					EjbFileUpload.saveImage(file);
					FacesMessage message = new FacesMessage("Ok","Fichero "+this.file.getFileName()+" subido correctmamente");
					FacesContext.getCurrentInstance().addMessage(null, message);
				} catch (Exception e) {
					// TODO: handle exception
					e.printStackTrace();
				}
			}
			else {
				FacesMessage message = new FacesMessage("Error","Fichero con formato no reconocido "+this.file.getContentType());
				FacesContext.getCurrentInstance().addMessage(null, message);
			}			
		}		
		else {
			FacesMessage message = new FacesMessage("Error","No ha seleccionado ningun archivo");
			FacesContext.getCurrentInstance().addMessage(null, message);
		}
	}
	
	public void TransferFile(String fileName, InputStream in){
		try {
			OutputStream out = new FileOutputStream(new File(/*path*/fileName));
			int reader = 0;
			byte[] bytes = new byte[(int)getFile().getSize()];
			while ((reader = in.read(bytes)) != -1) {
				out.write(bytes, 0, reader);
			}
			in.close();
			out.flush();
			out.close();
		} catch (IOException e) {
			// TODO: handle exception
			e.printStackTrace();
		}
	}
	
	public void handleFileUpload(FileUploadEvent event) throws IOException{
		try {
			///EjbFileUpload.saveImage(event.getFile());
			ResumenPedidoBase r = SessionHelper.getResumenPedidoSession("pedido");
			r.setImagen(event.getFile().getContents());
			this.disable = false;
			MessagesHelper.createMessage(event.getFile().getFileName()+ " is uploaded");/*
			FacesMessage message = new FacesMessage("Succesful",event.getFile().getFileName()+ " is uploaded");
			FacesContext.getCurrentInstance().addMessage(null, message);*/
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}		
	}
	
	public String isUpload(){
		String url="";
		FacesContext context = FacesContext.getCurrentInstance();
		ExternalContext exContext = context.getExternalContext();
		url = exContext.encodeActionURL(context.getApplication().getViewHandler().getActionURL(context, "/client/pago.xhtml"));
		try {
			exContext.redirect(url);
		} catch (IOException ie) {
			ie.printStackTrace();
		}
		return "success";
		
	}
	
	public void cancelarPedido(){
		if (SessionHelper.isSessionExist("pedido")) {
			SessionHelper.destroySession("pedido");
			UtilHelper.redirectUrl("/pages/index.xhtml");
		}
	}
	
	private UploadedFile file;
	private boolean disable;
}
